package com.cn.lyl.util;

import com.cn.lyl.dao.LawyerDao;
import com.cn.lyl.model.LawyerModel;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class LawyerFileOperation {

    public void writeFile(File file){

        LawyerDao dao = new LawyerDao();
        List<LawyerModel> lawyers = dao.LawyerList();
        try {
            OutputStream outputStream = new FileOutputStream(file);
            //outputStream.write(Integer.parseInt(Arrays.toString(lawyers.toArray())));
            for (LawyerModel lawyer:lawyers){
                outputStream.write((lawyer.toString()+"\n").getBytes());

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    };

    public File createFile(String path, String fileName){

        File parent = new File(path);
        if (!parent.exists()){
            parent.mkdirs();
        }
        File file = new File(parent,fileName);
        if (!file.exists()){
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;

    }


    public List<LawyerModel>  readFile(File file) {

        List <LawyerModel> lawyers =new ArrayList<LawyerModel>();
        String results ="";
        try {
            FileInputStream inputStream = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,"GBK"));

            int read = 0;
            while((read =reader.read())!= -1){
                results+= (char) read;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String[] lines =results.split("\n");
        for(String line : lines){
            lawyers.add(this.setLawyer(line));
        }
        return lawyers;
    }
    private LawyerModel setLawyer(String results){

        String[] result = results.split("@@@@@@@");
        LawyerModel lawyer = new LawyerModel(result[0],result[1],result[2],result[3]);
        return lawyer;
    }

}
